<?php
include("dbconnect.php");

$text = $_GET["noteArea"];
//echo $text;
$rid = $_GET["rid"];

$pattern = "/(#|@|\^|\*)(\w|\-)*|\w*\s|\w*/";
$parse = null;
//split the text into words
$returnValue = preg_match_all($pattern, $text, $parse);
print_r($parse);
echo "<br/>";

$html = "";
$tagArray = array();

foreach ($parse[0] as $term){
	//handle tags
	echo $term."<br/>";
	if (strpbrk($term, '#@^*')){
		//check database for tag
		//insert on duplicate key
		//get the type char
		$type = substr($term, 0, 1);
		echo $type."<br/>";
		//get the tag
		$tag = substr($term, 1);
		echo $tag."<br/>";
		//insert new unique tags into database
		$query = "INSERT IGNORE INTO tags (type, tag) VALUES ('".$type."', '".$tag."')";
		//get the tag id that was just created, if nothing was created 0 is returned
		$tid=queryserver($query);
		//get tag tid if existing tag
		if($tid==0){
			//get tag id
			$q = "SELECT tid FROM tags WHERE type ='". $type."' AND tag ='".$tag."'";
			$result = mysql_query($q) or die('Query failed: ' . mysql_error());
			while($l = mysql_fetch_array($result, MYSQL_ASSOC)) {
				$tid = $l[tid];
				echo $tid."<br/>";
			}
		}		
		//create link
		echo "creating link<br/>";
		$link = "<a href=\"search.php?tid=".urlencode($type).$tag."\">".$term."</a>";
		echo $link."<br/>";
		//add to html
		$html = $html.$link;
		//add tid to tagarray
		$tagArray[]=$tid;
	}//handle words and spaces
	else{
		//add to html
		$html = $html.$term;
	}		
	
}

echo $html;

//if rid(edit)
if($rid > 0){
	//mark current record as old
	$query = "UPDATE records SET version=0 WHERE rid='".$rid."'";
	queryserver($query);
	//submit record to db
	$query = "INSERT INTO records (text, html, time, version, previous) VALUES ('".$text."', '".$html."', NOW(), '1', '".$rid."')";
	$rid=queryserver($query);
}else//if no rid(new note)
{
	//submit record to db
	$query = "INSERT INTO records (text, html, time, version, previous) VALUES ('".$text."', '".$html."', NOW(), '1', '0')";
	$rid=queryserver($query);
}
echo $rid;

//update record-tag table
foreach ($tagArray as $tag){
	$query = "INSERT INTO record_tag (rid, tid) VALUES ('".$rid."', '".$tag."')";
	queryserver($query);
}

header( 'Location: index.php?rid='.$rid);
?>